﻿using AutoMapper;
using IOA.MES.Common;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.Enum;
using IOA.MES.DataAccess.VModel;
using IOA.MES.Log.Business;
using IOA.MES.Log.DataAccess.VModel;
using IOA.Utils;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace IOA.MES.Business
{
    /// <summary>
    /// 组件管理（错误代码：137001）
    /// </summary>
    public class ComponentMgr
    {
        private MESContext mesDb = new MESContext("MES");
        private Logger logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 生成组件
        /// </summary>
        /// <param name="model">生成对象</param>
        /// <param name="codes">多个条码规则</param>
        public void CreateComponents(VDistributeTask model, List<string> codes)
        {
            var workOrder = new WorkOrderMgr().GetWorkOrder(model.WorkOrderNo);
            if (workOrder == null)
            {
                throw new MultiLanBizException(102022, model.WorkOrderNo);// $"工单不存在：{model.WorkOrderNo}");
            }

            var codeEntities = new List<Component>();
            if (model.DistributeType == DistributeType.Single)
            {
                codeEntities.Add(new Component
                {
                    BarCode = model.SingleCode,
                });
            }
            else if (model.DistributeType == DistributeType.Multiple)
            {
                codes = codes ?? new List<string>();
                codeEntities.AddRange(codes.Select(_ => new Component
                {
                    BarCode = _
                }));
            }
            else
            {
                var format = "";
                for (int i = 0; i < model.SerialNumCount; i++)
                {
                    format = format + "0";
                }
                for (int i = model.StartNum.Value; i <= model.EndNum.Value; i++)
                {
                    codeEntities.Add(new Component
                    {
                        BarCode = $"{model.CodeFront}{i.ToString(format)}{model.CodeEnd}"
                    });
                }
            }

            var totalCodes = codeEntities.Select(_ => _.BarCode.ToUpper().Trim()).Distinct().ToList();
            var existCodes = mesDb.Components.AsNoTracking().Where(_ => totalCodes.Contains(_.BarCode) && _.Valid).ToList();
            if (existCodes.Any())
            {
                throw new MultiLanBizException(137001, string.Join("、", existCodes.Select(_ => _.BarCode)));// $"下列条码已存在：{string.Join("、", existCodes.Select(_ => _.Code))}");
            }

            codeEntities.ForEach(code =>
            {
                code.ProductStatus = ProductStatus.Normal;
                code.BarCode = code.BarCode.Trim().ToUpper();
                code.OrderNo = workOrder.OrderNo;
                code.CustomerCode = workOrder.CustomerCode;
                code.CustomerName = workOrder.CustomerName;
                code.WorkOrderNo = workOrder.WorkOrderNo;
                code.WorkshopCode = workOrder.WorkshopCode;
                code.WorkshopName = workOrder.WorkshopName;
                code.ProductCode = workOrder.ProductCode;
                code.ProductName = workOrder.ProductName;
                code.ProductSpecs = workOrder.ProductSpecs;
                code.CreateBy = model.CreateBy;
                code.CreateTime = DateTime.Now;
            });

            mesDb.Components.AddRange(codeEntities);
            mesDb.SaveChanges();

            new TaskFactory().StartNew(() =>
            {
                var user = new UserMgr().QueryUsers(new List<int> { model.CreateBy }).FirstOrDefault();
                var logs = codeEntities.Select(_ => new VOprLog
                {
                    SubjectType = "组件",
                    SubjectNo = _.BarCode,
                    LogName = "生成条码",
                    LogStatus = "正常",
                    OpeatorId = model.CreateBy,
                    OpeatorName = user?.TrueName,
                    LogContent = $"生成组件条码：{_.BarCode}，本次共生成{codeEntities.Count}个",
                    LogTime = DateTime.Now,
                    CreateBy = model.CreateBy
                }).ToList();
                new OprLogMgr().AddLogs(logs);
            });
        }

        /// <summary>
        /// 查询条码
        /// </summary>
        /// <param name="pageIndex">页面索引</param>
        /// <param name="pageSize">页面容量</param>
        /// <param name="total">总数量</param>
        /// <param name="orderNo">订单号</param>
        /// <param name="workOrderNo">工单号</param>
        /// <param name="workshopName">车间</param>
        /// <param name="code">条码</param>
        /// <returns>组件列表</returns>
        public List<VComponent> Components(int pageIndex, int pageSize, out int total, string orderNo, string workOrderNo, string workshopName, string code)
        {
            var query = mesDb.Components.AsNoTracking().Where(_ => _.Valid);
            if (!string.IsNullOrWhiteSpace(orderNo))
            {
                query = query.Where(_ => _.OrderNo.Contains(orderNo));
            }
            if (!string.IsNullOrWhiteSpace(workOrderNo))
            {
                query = query.Where(_ => _.WorkOrderNo.Contains(workOrderNo));
            }
            if (!string.IsNullOrWhiteSpace(workshopName))
            {
                query = query.Where(_ => _.WorkshopName.Contains(workshopName));
            }
            if (!string.IsNullOrWhiteSpace(code))
            {
                query = query.Where(_ => _.BarCode.Contains(code));
            }

            total = query.Count();

            query = query.OrderByDescending(_ => _.PkId);

            var entities = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            var models = Mapper.Map<List<VComponent>>(entities);

            var userIds = models.Select(_ => _.CreateBy).Distinct().ToList();
            var users = !userIds.Any() ? new List<VUser>() : new UserMgr().QueryUsers(userIds);

            models.ForEach(model =>
            {
                model.CNCreateBy = users.FirstOrDefault(_ => _.PkId == model.CreateBy)?.TrueName ?? string.Empty;
            });

            return models;
        }

        /// <summary>
        /// 查询所有组件
        /// </summary>
        /// <param name="cabinetNo">柜号</param>
        /// <param name="packNo">打包编号</param>
        /// <param name="barCode">组件条码</param>
        /// <returns>组件列表</returns>
        public List<VComponent> QueryComponents(string cabinetNo, string packNo, List<string> barCodes)
        {
            if (string.IsNullOrWhiteSpace(cabinetNo) && string.IsNullOrWhiteSpace(packNo) && !barCodes.Any())
            {
                return new List<VComponent>();
            }
            var query = mesDb.Components.AsNoTracking().Where(_ => _.Valid);
            if (!string.IsNullOrWhiteSpace(cabinetNo))
            {
                query = query.Where(_ => _.CabinetNo == cabinetNo);
            }
            if (!string.IsNullOrWhiteSpace(packNo))
            {
                query = query.Where(_ => _.PackNo == packNo);
            }
            if (barCodes.Any())
            {
                query = query.Where(_ => barCodes.Contains(_.BarCode));
            }
            return Mapper.Map<List<VComponent>>(query.ToList());
        }

        /// <summary>
        /// 查询回收的组件
        /// </summary>
        /// <param name="page">页面索引</param>
        /// <param name="limit">页面容量</param>
        /// <param name="total">全部数量</param>
        /// <param name="workshopCode">车间代码</param>
        /// <param name="orderNo">订单号</param>
        /// <param name="workOrderNo">工单号</param>
        /// <param name="barCode">条码</param>
        /// <returns>组件列表</returns>
        public List<VComponentRecycle> QueryRecycleComponents(int page, int limit, out int total, string workshopCode, string orderNo, string workOrderNo, string barCode)
        {
            var query = mesDb.ComponentRecycles.AsNoTracking().Where(_ => _.WorkshopCode == workshopCode && _.Valid);
            if (!string.IsNullOrWhiteSpace(barCode))
            {
                query = query.Where(_ => _.BarCode.Contains(barCode));
            }
            if (!string.IsNullOrWhiteSpace(orderNo))
            {
                query = query.Where(_ => _.OrderNo.Contains(orderNo));
            }
            if (!string.IsNullOrWhiteSpace(workOrderNo))
            {
                query = query.Where(_ => _.WorkOrderNo.Contains(workOrderNo));
            }
            total = query.Count();
            query = query.OrderByDescending(_ => _.PkId);

            var entities = limit <= 0 ? query.ToList() : query.Skip((page - 1) * limit).Take(limit).ToList();
            var models = Mapper.Map<List<VComponentRecycle>>(entities);
            var userIds = models.Select(_ => _.CreateBy).Distinct().ToList();
            var users = new UserMgr().QueryUsers(userIds);
            models.ForEach(_ =>
            {
                _.CNCreateBy = users.FirstOrDefault(u => u.PkId == _.CreateBy)?.TrueName;
            });
            return models;
        }

        /// <summary>
        /// 查询组件列表
        /// </summary>
        /// <param name="page">页面索引</param>
        /// <param name="limit">页面容量</param>
        /// <param name="total">全部数量</param>
        /// <param name="workOrderNo">工单号</param>
        /// <returns>组件列表</returns>
        public List<VComponent> QueryWorkOrderComponents(int page, int limit, out int total, string workOrderNo)
        {
            var query = mesDb.Components.AsNoTracking().Where(_ => _.WorkOrderNo == workOrderNo && _.Valid);

            total = query.Count();
            query = query.OrderByDescending(_ => _.PkId);
            var entities = limit <= 0 ? new List<Component>() : query.Skip((page - 1) * limit).Take(limit).ToList();
            return Mapper.Map<List<VComponent>>(entities);
        }

        /// <summary>
        /// 组件检索
        /// </summary>
        /// <param name="pageIndex">页面索引</param>
        /// <param name="pageSize">页面容量</param>
        /// <param name="total">总数量</param>
        /// <param name="orderNo">订单号</param>
        /// <param name="workOrderNo">工单号</param>
        /// <param name="cabinetNo">柜号</param>
        /// <param name="packNo">箱号</param>
        /// <param name="barCode">条码</param>
        /// <returns>组件列表</returns>
        public List<VComponent> QueryComponents(int pageIndex, int pageSize, out int total, string orderNo, string workOrderNo, string cabinetNo, string packNo, string barCode)
        {
            var query = mesDb.Components.AsNoTracking().Where(_ => _.Valid);
            var barCodes = (barCode ?? string.Empty).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(_ => _.ToUpper().Trim()).Distinct().ToList();
            var packNos = (packNo ?? string.Empty).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(_ => _.ToUpper().Trim()).Distinct().ToList();
            var cabinetNos = (cabinetNo ?? string.Empty).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(_ => _.ToUpper().Trim()).Distinct().ToList();
            if (barCodes.Any())
            {
                barCode = barCodes[0];
                query = barCodes.Count > 1 ? query.Where(_ => barCodes.Contains(_.BarCode))
                    : (barCode.Length >= 21 ? query.Where(_ => _.BarCode == barCode) : query.Where(_ => _.BarCode.Contains(barCode)));
            }
            else if (packNos.Any())
            {
                query = query.Where(_ => packNos.Contains(_.PackNo));
            }
            else if (cabinetNos.Any())
            {
                query = query.Where(_ => cabinetNos.Contains(_.CabinetNo));
            }
            else if (!string.IsNullOrWhiteSpace(workOrderNo))
            {
                query = query.Where(_ => _.WorkOrderNo.Contains(workOrderNo));
            }
            else if (!string.IsNullOrWhiteSpace(orderNo))
            {
                query = query.Where(_ => _.OrderNo.Contains(orderNo));
            }

            total = query.Count();
            query = query.OrderByDescending(_ => _.PkId).ThenByDescending(_ => _.BarCode);

            //导出或批量查询的时候，先查出全部
            var entities = pageSize <= 0 || barCodes.Count > 1 ? query.ToList() : query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            var models = Mapper.Map<List<VComponent>>(entities);

            //批量导出时按批量条码顺序排序
            if (barCodes.Count > 1)
            {
                models.Sort((VComponent a, VComponent b) =>
                {
                    return barCodes.IndexOf(a.BarCode) <= barCodes.IndexOf(b.BarCode) ? -1 : 1;
                });

                if (pageSize > 0)
                {
                    models = models.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                }
            }

            var userIds = models.Select(_ => _.CreateBy).Distinct().ToList();
            var users = !userIds.Any() ? new List<VUser>() : new UserMgr().QueryUsers(userIds);

            models.ForEach(model =>
            {
                model.CNCreateBy = users.FirstOrDefault(_ => _.PkId == model.CreateBy)?.TrueName ?? string.Empty;
            });

            return models;
        }

        /// <summary>
        /// 获取组件详情
        /// </summary>
        /// <param name="barCode">组件条码</param>
        /// <returns>组件详情</returns>
        public VComponent GetComponent(string barCode)
        {
            var entity = mesDb.Components.AsNoTracking().FirstOrDefault(_ => _.BarCode == barCode && _.Valid);
            if (entity == null)
            {
                return null;
            }
            var model = Mapper.Map<VComponent>(entity);
            var users = new UserMgr().QueryUsers(new List<int> { entity.CreateBy });
            model.CNCreateBy = users.FirstOrDefault(_ => _.PkId == _.CreateBy)?.TrueName;
            return model;
        }

        /// <summary>
        /// 查询包装组件列表
        /// </summary>
        /// <param name="packNo">打包编号</param>
        /// <returns></returns>
        public List<VComponent> QueryPackComponents(string packNo)
        {
            var components = mesDb.Components.AsNoTracking().Where(_ => _.PackNo == packNo && _.Valid).ToList();
            return Mapper.Map<List<VComponent>>(components);
        }

        /// <summary>
        /// 回收条码
        /// </summary>
        /// <param name="model">回收对象</param>
        public void RecycleBarCode(VComponentRecycle model)
        {
            var component = mesDb.Components.AsNoTracking().FirstOrDefault(_ => _.BarCode == model.BarCode && _.Valid);
            if (component == null)
            {
                throw new MultiLanBizException(137002);//条码不存在
            }
            else if (component.ProductStatus == ProductStatus.Recycled)
            {
                throw new MultiLanBizException(137003);//该条码已被回收，无法重复操作
            }
            else if (!string.IsNullOrWhiteSpace(component.PackNo))
            {
                throw new MultiLanBizException(137004, component.PackNo);//当前组件已打包，请解包后再回收，打包编号为
            }

            model.WorkshopCode = component.WorkshopCode;
            model.WorkshopName = component.WorkshopName;
            model.ProductCode = component.ProductCode;
            model.ProductName = component.ProductName;
            model.OrderNo = component.OrderNo;
            model.WorkOrderNo = component.WorkOrderNo;
            model.CreateTime = DateTime.Now;

            mesDb.ComponentRecycles.Add(Mapper.Map<ComponentRecycle>(model));
            mesDb.SaveChanges();

            new TaskFactory().StartNew(() =>
            {
                mesDb.Components.Attach(component);
                component.ModifyBy = model.CreateBy;
                component.ModifyTime = DateTime.Now;

                #region 初始化组件数据
                #region 初始化分片数据
                component.DistributeTime = null;
                component.LastSite = null;
                component.LastSiteTime = null;
                component.ProductStatus = ProductStatus.Recycled;
                component.ProduceStatus = ProduceStatus.NotProduced;
                component.CellArea = 0;
                component.CellEfficiency = 0;
                component.SinglePiecePower = 0;
                component.TheoreticalPower = 0;
                component.CellColor = string.Empty;
                component.ComponentColor = string.Empty;
                component.CellBoxNo = string.Empty;
                #endregion

                #region 初始化焊接参数
                component.LineId = 0;
                component.LineName = string.Empty;

                component.WeldingTime = null;
                component.WeldingLineId = 0;
                component.WeldingLine = string.Empty;
                component.WeldingDutyId = 0;
                component.WeldingDuty = string.Empty;
                component.WeldingMachineId = 0;
                component.WeldingMachine = string.Empty;
                component.WeldingUser = string.Empty;
                #endregion

                #region 初始化叠层参数
                component.BackPlanSpecs = string.Empty;
                component.BackPlanFactory = string.Empty;
                component.LaminatedTime = null;
                component.LaminatedLineId = 0;
                component.LaminatedLine = string.Empty;
                component.LaminatedDutyId = 0;
                component.LaminatedDuty = string.Empty;
                component.LaminatedMachineId = 0;
                component.LaminatedMachine = string.Empty;
                component.LaminatedUser = string.Empty;
                #endregion

                #region 初始化EL1参数
                component.EL1OncePass = null;
                component.EL1Image = string.Empty;
                component.EL1Time = null;
                component.EL1LineId = 0;
                component.EL1Line = string.Empty;
                component.EL1DutyId = 0;
                component.EL1Duty = string.Empty;
                component.EL1MachineId = 0;
                component.EL1Machine = string.Empty;
                component.EL1User = string.Empty;
                #endregion

                #region 初始化层压参数
                component.TopTime = null;
                component.TopLineId = 0;
                component.TopLine = string.Empty;
                component.TopDutyId = 0;
                component.TopDuty = string.Empty;
                component.TopMachineId = 0;
                component.TopMachine = string.Empty;
                component.TopUser = string.Empty;
                component.TopPosition = string.Empty;
                #endregion

                #region 初始化NQC
                component.NQCOncePass = null;
                component.NQCTime = null;
                component.NQCLineId = 0;
                component.NQCLine = string.Empty;
                component.NQCDutyId = 0;
                component.NQCDuty = string.Empty;
                component.NQCMachineId = 0;
                component.NQCMachine = string.Empty;
                component.NQCUser = string.Empty;
                #endregion

                #region 初始化接线盒拍照
                component.BoxImage = string.Empty;
                component.FramingTime = null;
                component.FramingLineId = 0;
                component.FramingLine = string.Empty;
                component.FramingDutyId = 0;
                component.FramingDuty = string.Empty;
                component.FramingMachineId = 0;
                component.FramingMachine = string.Empty;
                component.FramingUser = string.Empty;
                component.JunBoxSpecs = string.Empty;
                component.JunBoxFactory = string.Empty;
                component.AluFrameSpecs = string.Empty;
                component.AluFrameFactory = string.Empty;
                #endregion

                #region 初始化清洗
                component.CleanTime = null;
                component.CleanLineId = 0;
                component.CleanLine = string.Empty;
                component.CleanDutyId = 0;
                component.CleanDuty = string.Empty;
                component.CleanMachineId = 0;
                component.CleanMachine = string.Empty;
                component.CleanUser = string.Empty;
                #endregion

                #region 初始化IV数据记录
                component.IvImage = string.Empty;
                component.NameplateModel = string.Empty;
                component.IVPowerLevel = null;
                component.IVCurrentLevel = string.Empty;
                component.ConversionEfficiency = 0;
                component.Isc = null;
                component.Voc = null;
                component.Vm = null;
                component.Im = null;
                component.FF = null;
                component.Pmax = null;
                component.Temp = null;
                component.Ress = null;
                component.Ressh = null;
                component.ModEff = null;
                component.SunRef = null;
                component.IVTestTime = null;
                component.IVTestLineId = 0;
                component.IVTestLine = string.Empty;
                component.IVTestDutyId = 0;
                component.IVTestDuty = string.Empty;
                component.IVTestMachineId = 0;
                component.IVTestMachine = string.Empty;
                component.IVTestUser = string.Empty;
                #endregion

                #region 初始化绝缘耐压数据记录
                component.InsulatedResistanceTime = null;
                component.InsulatedResistanceLineId = 0;
                component.InsulatedResistanceLine = string.Empty;
                component.InsulatedResistanceDutyId = 0;
                component.InsulatedResistanceDuty = string.Empty;
                component.InsulatedResistanceMachineId = 0;
                component.InsulatedResistanceMachine = string.Empty;
                component.InsulatedResistanceUser = string.Empty;
                #endregion

                #region 初始化EL2拍照
                component.EL2OncePass = null;
                component.EL2Image = string.Empty;
                component.EL2Time = null;
                component.EL2LineId = 0;
                component.EL2Line = string.Empty;
                component.EL2DutyId = 0;
                component.EL2Duty = string.Empty;
                component.EL2MachineId = 0;
                component.EL2Machine = string.Empty;
                component.EL2User = string.Empty;
                #endregion

                #region 初始化铭牌打印
                component.NameplatePrintingTime = null;
                component.NameplatePrintingLineId = 0;
                component.NameplatePrintingLine = string.Empty;
                component.NameplatePrintingDutyId = 0;
                component.NameplatePrintingDuty = string.Empty;
                component.NameplatePrintingMachineId = 0;
                component.NameplatePrintingMachine = string.Empty;
                component.NameplatePrintingUser = string.Empty;
                #endregion

                #region 初始化终检
                component.FinalInspectionOncePass = null;
                component.QLevel = string.Empty;
                component.FinalInspectionTime = null;
                component.FinalInspectionLineId = 0;
                component.FinalInspectionLine = string.Empty;
                component.FinalInspectionDutyId = 0;
                component.FinalInspectionDuty = string.Empty;
                component.FinalInspectionMachineId = 0;
                component.FinalInspectionMachine = string.Empty;
                component.FinalInspectionUser = string.Empty;
                component.FinalInspectionCellFeature = string.Empty;
                component.FinalInspectionComponentType = string.Empty;
                component.FinalInspectionBadReason = string.Empty;
                #endregion

                #region 初始化打包
                component.PackTime = null;
                component.PackLineId = 0;
                component.PackLine = string.Empty;
                component.PackDutyId = 0;
                component.PackDuty = string.Empty;
                component.PackMachineId = 0;
                component.PackMachine = string.Empty;
                component.PackUser = string.Empty;
                #endregion
                #endregion

                var distributeCodes = mesDb.DistributeCodes.AsNoTracking().Where(_ => _.Code == model.BarCode && _.Valid).ToList();
                var distributeCodeOperates = mesDb.DistributeCodeOperates.AsNoTracking().Where(_ => _.Code == model.BarCode && _.Valid).ToList();
                var records = mesDb.ProductViaSiteRecords.AsNoTracking().Where(_ => _.Code == model.BarCode && _.Valid).ToList();
                var weldingRecords = mesDb.ProductViaSiteWeldDatas.AsNoTracking().Where(_ => _.BarCode == model.BarCode && _.Valid).ToList();
                var ivRecords = mesDb.ProductViaSiteIVDatas.AsNoTracking().Where(_ => _.BarCode == model.BarCode && _.Valid).ToList();
                var topRecords = mesDb.ProductViaSiteTopDatas.AsNoTracking().Where(_ => _.BarCode == model.BarCode && _.Valid).ToList();
                var inRecords = mesDb.ProductViaSiteInsulateDatas.AsNoTracking().Where(_ => _.BarCode == model.BarCode && _.Valid).ToList();
                var images = mesDb.ProductViaSiteImages.AsNoTracking().Where(_ => _.BarCode == model.BarCode && _.Valid).ToList();

                distributeCodes.ForEach(_ =>
                {
                    mesDb.DistributeCodes.Attach(_);
                    _.Valid = false;
                    _.ModifyBy = model.CreateBy;
                    _.ModifyTime = DateTime.Now;
                });
                distributeCodeOperates.ForEach(_ =>
                {
                    mesDb.DistributeCodeOperates.Attach(_);
                    _.Valid = false;
                    _.ModifyBy = model.CreateBy;
                    _.ModifyTime = DateTime.Now;
                });
                records.ForEach(_ =>
                {
                    mesDb.ProductViaSiteRecords.Attach(_);
                    _.Valid = false;
                    _.ModifyBy = model.CreateBy;
                    _.ModifyTime = DateTime.Now;
                });
                weldingRecords.ForEach(_ =>
                {
                    mesDb.ProductViaSiteWeldDatas.Attach(_);
                    _.Valid = false;
                    _.ModifyBy = model.CreateBy;
                    _.ModifyTime = DateTime.Now;
                });
                ivRecords.ForEach(_ =>
                {
                    mesDb.ProductViaSiteIVDatas.Attach(_);
                    _.Valid = false;
                    _.ModifyBy = model.CreateBy;
                    _.ModifyTime = DateTime.Now;
                });
                topRecords.ForEach(_ =>
                {
                    mesDb.ProductViaSiteTopDatas.Attach(_);
                    _.Valid = false;
                    _.ModifyBy = model.CreateBy;
                    _.ModifyTime = DateTime.Now;
                });
                inRecords.ForEach(_ =>
                {
                    mesDb.ProductViaSiteInsulateDatas.Attach(_);
                    _.Valid = false;
                    _.ModifyBy = model.CreateBy;
                    _.ModifyTime = DateTime.Now;
                });
                images.ForEach(_ =>
                {
                    mesDb.ProductViaSiteImages.Attach(_);
                    _.Valid = false;
                    _.ModifyBy = model.CreateBy;
                    _.ModifyTime = DateTime.Now;
                });
                mesDb.SaveChanges();

                var user = new UserMgr().QueryUsers(new List<int> { model.CreateBy }).FirstOrDefault();
                new OprLogMgr().AddLogs(new List<VOprLog> { new VOprLog
                {
                    SubjectType = "组件",
                    SubjectNo = model.BarCode,
                    LogName = "回收",
                    LogStatus = "异常",
                    OpeatorId = model.CreateBy,
                    OpeatorName = user?.TrueName,
                    LogContent = $"组件回收：{model.BarCode}，过站数据已被初始化",
                    LogTime = DateTime.Now,
                    CreateBy = model.CreateBy
                }});
            });
        }
    }
}
